//创建用户相关的仓库
import { defineStore } from 'pinia'

//调用用户登录接口
import { reqLogin, reqUserInfo, reqLogut } from '@/api/user'

// import type { LoginFormData, LoginResponseData } from '@/api/user/types'
import {
  loginFormData,
  loginResponseData,
  userinfoResData,
  ResponseData,
} from '@/api/user/types'
import { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constRouter } from '@/router/routes'

//创建用户相关的小仓库
let userStore = defineStore('User', {
  //存储用户数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      userMenus: constRouter, // 当前用户的菜单
      name: '',
      avator: '',
    }
  },

  //异步逻辑执行的地方
  actions: {
    //用户登录方法
    async login(data: loginFormData) {
      // console.log(123)
      //登录请求
      const res: loginResponseData = await reqLogin(data)
      // console.log(res)

      if (res.code == 200) {
        //获取登录成功返回的token
        const token = res.data as string
        this.token = token
        //本地存储持久化
        SET_TOKEN(token)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    async userInfo() {
      const res: userinfoResData = await reqUserInfo()
      // console.log(res)
      if (res.code == 200) {
        this.name = res.data.name
        this.avator = res.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async exitSys() {
      const res: ResponseData = await reqLogut()
      // console.log(res);
      if (res.code == 200) {
        this.name = ''
        this.avator = ''
        this.token = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})

//对外暴露获取小仓库的方法
export default userStore
